#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from PySide6.QtWidgets import (
    QMainWindow, QSystemTrayIcon, QMenu, 
    QVBoxLayout, QHBoxLayout, QWidget, QLabel, 
    QProgressBar, QPushButton, QStackedWidget
)
from PySide6.QtGui import QIcon, QAction, QFont
from PySide6.QtCore import Qt, QSize, QTimer

from app.models.timer import Timer, TimerState, TimerMode
from app.components.break_dialog import BreakDialog
from app.components.settings_dialog import SettingsDialog
from app.components.stats_dialog import StatsDialog

class MainWindow(QMainWindow):
    """应用程序主窗口"""
    
    def __init__(self, config_manager, db_manager):
        """初始化主窗口
        
        Args:
            config_manager: 配置管理器实例
            db_manager: 数据库管理器实例
        """
        super().__init__()
        
        self.config_manager = config_manager
        self.db_manager = db_manager
        
        # 创建计时器模型
        self.timer = Timer(config_manager, db_manager)
        self.timer.stateChanged.connect(self._on_timer_state_changed)
        self.timer.tick.connect(self._on_timer_tick)
        self.timer.workFinished.connect(self._on_work_finished)
        self.timer.breakFinished.connect(self._on_break_finished)
        
        # 设置窗口属性
        self.setWindowTitle("兔子休息提醒")
        self.setWindowIcon(QIcon("app/resources/icons/bunny.png"))
        self.setMinimumSize(400, 300)
        
        # 创建UI组件
        self._create_ui()
        
        # 创建系统托盘图标
        self._create_tray_icon()
        
        # 更新UI状态
        self._update_ui_state()
        
        # 显示窗口
        if not config_manager.get("general", "minimize_to_tray"):
            self.show()
    
    def _create_ui(self):
        """创建UI组件"""
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(15)
        
        # 创建模式切换按钮
        mode_layout = QHBoxLayout()
        self.pomodoro_button = QPushButton("番茄钟模式")
        self.pomodoro_button.setCheckable(True)
        self.pomodoro_button.clicked.connect(lambda: self._switch_mode(TimerMode.POMODORO))
        
        self.flowdoro_button = QPushButton("Flowdoro模式")
        self.flowdoro_button.setCheckable(True)
        self.flowdoro_button.clicked.connect(lambda: self._switch_mode(TimerMode.FLOWDORO))
        
        mode_layout.addWidget(self.pomodoro_button)
        mode_layout.addWidget(self.flowdoro_button)
        main_layout.addLayout(mode_layout)
        
        # 创建状态标签
        self.status_label = QLabel("准备开始")
        self.status_label.setAlignment(Qt.AlignCenter)
        font = QFont()
        font.setPointSize(14)
        font.setBold(True)
        self.status_label.setFont(font)
        main_layout.addWidget(self.status_label)
        
        # 创建时间标签
        self.time_label = QLabel("00:00")
        self.time_label.setAlignment(Qt.AlignCenter)
        font = QFont()
        font.setPointSize(36)
        font.setBold(True)
        self.time_label.setFont(font)
        main_layout.addWidget(self.time_label)
        
        # 创建进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        self.progress_bar.setTextVisible(False)
        main_layout.addWidget(self.progress_bar)
        
        # 创建统计信息标签
        stats_layout = QHBoxLayout()
        self.today_work_label = QLabel("今日工作: 0小时0分钟")
        self.today_pomodoros_label = QLabel("完成番茄: 0")
        stats_layout.addWidget(self.today_work_label)
        stats_layout.addWidget(self.today_pomodoros_label)
        main_layout.addLayout(stats_layout)
        
        # 创建控制按钮
        control_layout = QHBoxLayout()
        
        self.start_button = QPushButton("开始工作")
        self.start_button.clicked.connect(self._on_start_clicked)
        
        self.pause_button = QPushButton("暂停")
        self.pause_button.clicked.connect(self._on_pause_clicked)
        
        self.stop_button = QPushButton("停止")
        self.stop_button.clicked.connect(self._on_stop_clicked)
        
        control_layout.addWidget(self.start_button)
        control_layout.addWidget(self.pause_button)
        control_layout.addWidget(self.stop_button)
        
        main_layout.addLayout(control_layout)
        
        # 创建设置和统计按钮
        bottom_layout = QHBoxLayout()
        
        self.settings_button = QPushButton("设置")
        self.settings_button.clicked.connect(self._on_settings_clicked)
        
        self.stats_button = QPushButton("统计")
        self.stats_button.clicked.connect(self._on_stats_clicked)
        
        bottom_layout.addWidget(self.settings_button)
        bottom_layout.addWidget(self.stats_button)
        
        main_layout.addLayout(bottom_layout)
        
        # 更新今日统计
        self._update_today_stats()
    
    def _create_tray_icon(self):
        """创建系统托盘图标"""
        # 创建托盘图标
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(QIcon("app/resources/icons/bunny.png"))
        self.tray_icon.setToolTip("兔子休息提醒")
        
        # 创建托盘菜单
        tray_menu = QMenu()
        
        # 添加菜单项
        show_action = QAction("显示主窗口", self)
        show_action.triggered.connect(self.show)
        
        start_work_action = QAction("开始工作", self)
        start_work_action.triggered.connect(self.timer.start_work)
        
        pause_action = QAction("暂停", self)
        pause_action.triggered.connect(self.timer.pause)
        
        resume_action = QAction("继续", self)
        resume_action.triggered.connect(self.timer.resume)
        
        stop_action = QAction("停止", self)
        stop_action.triggered.connect(self.timer.stop)
        
        mode_menu = QMenu("切换模式")
        pomodoro_action = QAction("番茄钟模式", self)
        pomodoro_action.triggered.connect(lambda: self._switch_mode(TimerMode.POMODORO))
        
        flowdoro_action = QAction("Flowdoro模式", self)
        flowdoro_action.triggered.connect(lambda: self._switch_mode(TimerMode.FLOWDORO))
        
        mode_menu.addAction(pomodoro_action)
        mode_menu.addAction(flowdoro_action)
        
        settings_action = QAction("设置", self)
        settings_action.triggered.connect(self._on_settings_clicked)
        
        stats_action = QAction("统计", self)
        stats_action.triggered.connect(self._on_stats_clicked)
        
        exit_action = QAction("退出", self)
        exit_action.triggered.connect(self.close)
        
        # 添加菜单项到菜单
        tray_menu.addAction(show_action)
        tray_menu.addSeparator()
        tray_menu.addAction(start_work_action)
        tray_menu.addAction(pause_action)
        tray_menu.addAction(resume_action)
        tray_menu.addAction(stop_action)
        tray_menu.addSeparator()
        tray_menu.addMenu(mode_menu)
        tray_menu.addSeparator()
        tray_menu.addAction(settings_action)
        tray_menu.addAction(stats_action)
        tray_menu.addSeparator()
        tray_menu.addAction(exit_action)
        
        # 设置托盘菜单
        self.tray_icon.setContextMenu(tray_menu)
        
        # 连接信号
        self.tray_icon.activated.connect(self._on_tray_icon_activated)
        
        # 显示托盘图标
        self.tray_icon.show()
    
    def _switch_mode(self, mode):
        """切换计时器模式
        
        Args:
            mode: TimerMode 枚举值
        """
        # 如果计时器正在运行，先停止
        if self.timer.state != TimerState.IDLE:
            self.timer.stop()
        
        # 设置模式
        self.timer.set_mode(mode)
        
        # 更新UI
        self._update_ui_state()
    
    def _update_ui_state(self):
        """更新UI状态"""
        # 更新模式按钮
        self.pomodoro_button.setChecked(self.timer.mode == TimerMode.POMODORO)
        self.flowdoro_button.setChecked(self.timer.mode == TimerMode.FLOWDORO)
        
        # 更新状态标签
        if self.timer.state == TimerState.IDLE:
            self.status_label.setText("准备开始")
        elif self.timer.state == TimerState.WORKING:
            self.status_label.setText("工作中")
        elif self.timer.state == TimerState.BREAKING:
            self.status_label.setText("休息中")
        elif self.timer.state == TimerState.PAUSED:
            self.status_label.setText("已暂停")
        
        # 更新时间标签
        self.time_label.setText(self.timer.get_formatted_time())
        
        # 更新进度条
        self.progress_bar.setValue(int(self.timer.get_progress() * 100))
        
        # 更新按钮状态
        self.start_button.setEnabled(self.timer.state in [TimerState.IDLE, TimerState.PAUSED])
        self.pause_button.setEnabled(self.timer.state in [TimerState.WORKING, TimerState.BREAKING])
        self.stop_button.setEnabled(self.timer.state != TimerState.IDLE)
        
        # 更新开始按钮文本
        if self.timer.state == TimerState.IDLE:
            self.start_button.setText("开始工作")
        elif self.timer.state == TimerState.PAUSED:
            self.start_button.setText("继续")
    
    def _update_today_stats(self):
        """更新今日统计信息"""
        stats = self.db_manager.get_today_stats()
        
        # 计算工作时间
        total_work_minutes = stats['total_work_seconds'] // 60
        work_hours = total_work_minutes // 60
        work_minutes = total_work_minutes % 60
        
        # 更新标签
        self.today_work_label.setText(f"今日工作: {work_hours}小时{work_minutes}分钟")
        self.today_pomodoros_label.setText(f"完成番茄: {stats['completed_pomodoros']}")
    
    def _on_timer_state_changed(self, state):
        """计时器状态变化事件处理
        
        Args:
            state: 新的计时器状态
        """
        self._update_ui_state()
    
    def _on_timer_tick(self, remaining_seconds, total_seconds):
        """计时器滴答事件处理
        
        Args:
            remaining_seconds: 剩余时间（秒）
            total_seconds: 总时间（秒）
        """
        # 更新时间标签
        self.time_label.setText(self.timer.get_formatted_time())
        
        # 更新进度条
        self.progress_bar.setValue(int(self.timer.get_progress() * 100))
    
    def _on_work_finished(self):
        """工作完成事件处理"""
        # 更新今日统计
        self._update_today_stats()
        
        # 显示休息提醒对话框
        dialog = BreakDialog(self.config_manager, self)
        dialog.breakStarted.connect(self.timer.start_break)
        dialog.breakSkipped.connect(self._on_break_skipped)
        
        # 如果配置了自动开始休息，则自动开始
        if self.config_manager.get("general", "auto_start_break"):
            QTimer.singleShot(0, self.timer.start_break)
        
        dialog.exec()
    
    def _on_break_finished(self):
        """休息完成事件处理"""
        # 更新今日统计
        self._update_today_stats()
        
        # 如果配置了自动开始工作，则自动开始
        if self.config_manager.get("general", "auto_start_work"):
            QTimer.singleShot(0, self.timer.start_work)
    
    def _on_break_skipped(self):
        """休息跳过事件处理"""
        # 如果配置了自动开始工作，则自动开始
        if self.config_manager.get("general", "auto_start_work"):
            QTimer.singleShot(0, self.timer.start_work)
    
    def _on_start_clicked(self):
        """开始按钮点击事件处理"""
        if self.timer.state == TimerState.PAUSED:
            self.timer.resume()
        else:
            self.timer.start_work()
    
    def _on_pause_clicked(self):
        """暂停按钮点击事件处理"""
        self.timer.pause()
    
    def _on_stop_clicked(self):
        """停止按钮点击事件处理"""
        self.timer.stop()
    
    def _on_settings_clicked(self):
        """设置按钮点击事件处理"""
        dialog = SettingsDialog(self.config_manager, self)
        dialog.exec()
    
    def _on_stats_clicked(self):
        """统计按钮点击事件处理"""
        dialog = StatsDialog(self.db_manager, self)
        dialog.exec()
    
    def _on_tray_icon_activated(self, reason):
        """托盘图标激活事件处理
        
        Args:
            reason: 激活原因
        """
        if reason == QSystemTrayIcon.ActivationReason.Trigger:
            # 单击托盘图标，切换窗口显示状态
            if self.isVisible():
                self.hide()
            else:
                self.show()
                self.activateWindow()
    
    def closeEvent(self, event):
        """窗口关闭事件处理
        
        Args:
            event: 关闭事件
        """
        if self.config_manager.get("general", "minimize_to_tray") and self.tray_icon.isVisible():
            # 如果配置了最小化到托盘，则隐藏窗口而不是关闭应用程序
            event.ignore()
            self.hide()
        else:
            # 关闭应用程序
            self.tray_icon.hide()
            event.accept() 